package com.fyzk.activity.user.xiangxi;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.bean.ChaseBuyOrderDetailResponse;
import com.fyzk.bean.ChasebuyBean;
import com.fyzk.dialog.DJ_ProgressDialog;
import com.fyzk.dialog.SureDialog;
import com.fyzk.dialog.SureDialog.OnDialogOKCancleClickListener;
import com.fyzk.interfaces.onTopTitleClickListener;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.net.PublicMethod;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

/**
 * 追号详情页
 */

@ContentView(R.layout.dj_zhuihao_detail)
public class ZhuihaoDetailActivity extends BaseActivity implements onTopTitleClickListener,
        AdapterView.OnItemClickListener {
    private TopTitleView topView;

    private String orderId;
    private int phases;
    private int amt;
    private int phased;
    private boolean prizeend;
    private String lotteryName;
    private String status;

    @ViewInject(R.id.lv_chasebuylist)
    private ListView lv_chasebuylist;
    @ViewInject(R.id.tv_phase_content)
    private TextView tv_phase_content;

    @ViewInject(R.id.tv_phase_title)
    private TextView tv_phase_title;

    @ViewInject(R.id.tv_phase_amount)
    private TextView tv_phase_amount;

    @ViewInject(R.id.tv_phase_status)
    private TextView tv_phase_status;

    @ViewInject(R.id.tv_phase_prizeend)
    private TextView tv_phase_prizeend;



    /**
     * 确认取消追号对话框
     */
    private SureDialog sureCancelDialog = null;

    List<ChasebuyBean> chasebuyBeens;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    protected void init() {
        // TODO Auto-generated method stub
        super.init();
        orderId = getIntent().getStringExtra(IntentParamUtils.BETDETAILID);
        phases = getIntent().getIntExtra(IntentParamUtils.CHASE, 1);
        amt = getIntent().getIntExtra(IntentParamUtils.AMT, 1);
        phased = getIntent().getIntExtra(IntentParamUtils.CHASEED, 1);
        prizeend = getIntent().getBooleanExtra(IntentParamUtils.PRIZEEND,false);
        status = getIntent().getStringExtra(IntentParamUtils.STATE);
        lotteryName = getIntent().getStringExtra(IntentParamUtils.LOTTERYNAME);

        topView = (TopTitleView) findViewById(R.id.order_topview);
        tv_phase_title.setText(lotteryName);
        tv_phase_amount.setText("订单彩金："+PublicMethod.formatMoney(amt)+"米");
        topView.setRightVisible(View.INVISIBLE);
        topView.setOnTitleClickListener(this);
        tv_phase_status.setText("订单状态："+status);
        if(prizeend){
            tv_phase_prizeend.setText("停追条件：中奖后停止");
        }else{
            tv_phase_prizeend.setText("停追条件：到期后停止");
        }

        tv_phase_content.setText("总追期" + phases + "期,已追" + phased + "期");
        lv_chasebuylist.setOnItemClickListener(this);
        chaseBuyList();
    }


    private void chaseBuyList() {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("chaseId", orderId)
            ;    // 查询类型 (-1不限 1未中奖 2中奖 3未开奖 4撤单)
            request_json.put("pageIndex", 1);
            request_json.put("maxResult", phases);
            httpPostJson(CommandUtil.ZHUIHAO_DETIAL, Commands.ZHUIHAO_DETIAL, request_json,
                    true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消某期追号
     *
     * @param chaseBuyId
     */
    private void cancelId(String chaseBuyId) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("chaseBuyId", chaseBuyId);
            httpPostJson(CommandUtil.CHASEBUYCANCEL, Commands.CHASEBUYCANCEL, request_json,
                    true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.ZHUIHAO_DETIAL:
                ChaseBuyOrderDetailResponse response = JSON.parseObject(resultBean.getData(), ChaseBuyOrderDetailResponse.class);
                chasebuyBeens = response.getChasebuy();
                lv_chasebuylist.setAdapter(new ChasebuyBeanListAdapter(chasebuyBeens));
                break;
            case CommandUtil.CHASEBUYCANCEL:
                AppToast.getToast().show("已撤销");
                chaseBuyList();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ChasebuyBean bean = chasebuyBeens.get(position);
        if (TextUtil.isEmpty(bean.getOrderid())) {
            AppToast.getToast().show("未出票");
        } else {
            Intent intent = new Intent(ZhuihaoDetailActivity.this, NumLotteryOrderDetailActivity.class);
            intent.putExtra(IntentParamUtils.BETDETAILID, bean.getOrderid());
            startActivity(intent);
        }
    }


    class ChasebuyBeanListAdapter extends BaseAdapter {

        List<ChasebuyBean> chasebuyBeens;

        public ChasebuyBeanListAdapter(List<ChasebuyBean> chasebuyBeens) {
            this.chasebuyBeens = chasebuyBeens;
        }

        @Override
        public int getCount() {
            return chasebuyBeens.size();
        }

        @Override
        public Object getItem(int position) {
            return chasebuyBeens.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(ZhuihaoDetailActivity.this, R.layout.layout_chasebet_item, null);
                holder = new ViewHolder();
                holder.index = convertView.findViewById(R.id.index);
                holder.phase = convertView.findViewById(R.id.phase);
                holder.statusName = convertView.findViewById(R.id.statusName);
                holder.prize = convertView.findViewById(R.id.prize);
                holder.amount = convertView.findViewById(R.id.amount);
                holder.cancel_btn = convertView.findViewById(R.id.cancel_btn);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final ChasebuyBean bean = chasebuyBeens.get(position);
            holder.amount.setText("追号:" + PublicMethod.formatMoney(bean.getAmount()) + "米");
            holder.index.setText((position + 1) + "");
            holder.phase.setText("第" + bean.getPhase() + "期");
            holder.prize.setTextColor(getResources().getColor(R.color.black));

            if (bean.getPrize() != 0) {
                holder.prize.setText("中" + PublicMethod.formatMoney(bean.getPrize()) + "米");
                holder.prize.setTextColor(getResources().getColor(R.color.red));
            } else if (TextUtil.isEmpty(bean.getOrderid())) {
                holder.prize.setText("未出票");
            } else {
                holder.prize.setText(bean.getPrizeName());
            }

            if (bean.getStatus() == 1) {
                holder.cancel_btn.setVisibility(View.VISIBLE);
            } else {
                holder.cancel_btn.setVisibility(View.GONE);
            }

            holder.statusName.setText(bean.getStatusName());

            holder.cancel_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showSureCancelZhuiHaoDialog(bean.getId());
                }
            });

            return convertView;
        }

        class ViewHolder {
            TextView index;
            TextView phase;
            TextView statusName;
            TextView amount;
            TextView prize;
            TextView cancel_btn;
        }

    }


    private void initViewData() {
        // TODO Auto-generated method stub
//		tv_caiZhong.setValue("" + getStringFromStream(AppLotteryInfos.getLotteryName(getLotteryId
// (responseObj.content))));
//		tv_money.setValue("" + responseObj.amount);
//		tv_phaseNum.setValue(""+responseObj.zhuiNum);
//		if (responseObj.isPrizeStop.equals("1")) {
//			tv_isPrizeStop.setValue("是");
//		}else{
//			tv_isPrizeStop.setValue("否");
//		}
//		tv_id.setValue("" + orderId);
//		tv_time.setValue("" + responseObj.time);
//		tv_state.setValue("" + ConstantsDJ.zhuiHao_state(responseObj.status));
//		tv_prizeMoney.setValue("" + responseObj.prizeAmount);
//
//		ll_content.removeAllViews();
//		View view = RaceFactory.getRaceView(getLotteryId(responseObj.content)).getZhuiHaoRaceView
// (getContext(),
//				responseObj.content, responseObj.races);
//		if (view != null) {
//			ll_content.addView(view);
//		}
//
//		if (!responseObj.status.equals("1")) {
//			tv_cancel.setVisibility(View.GONE);
//		}
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.zhuihao_xiangxi_jixu:
////			if (ContinueBuy.jiXu(getContext(), getLotteryId(responseObj.content))) {
////				finish();
////			}
//                break;
//            case R.id.zhuihao_xiangxi_cancle:
//                showSureCancelZhuiHaoDialog();
//                break;
            default:
                break;
        }
    }

    @Override
    public void onLeftClick() {
        // TODO Auto-generated method stub
        finish();
    }

    @Override
    public void onCenterClick() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onRightClick() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onRight2Click() {
        // TODO Auto-generated method stub

    }

    private String getLotteryId(String content) {
        if (content != null && !content.equals("") && content.contains("-")) {
            String wanFaId = content.split("-")[0];
            return wanFaId.substring(0, 4);
        } else {
            return "";
        }
    }

    private String getWanFaId(String content) {
        if (content != null && !content.equals("") && content.contains("-")) {
            return content.split("-")[0];
        } else {
            return "";
        }
    }

    /**
     * 确认撤单对话框
     */
    private void showSureCancelZhuiHaoDialog(final String chaseBuyId) {

        sureCancelDialog = new SureDialog(this, new OnDialogOKCancleClickListener() {

            @Override
            public void onOKClick() {
                DJ_ProgressDialog.show(getContext(), true, true);
                cancelId(chaseBuyId);
                sureCancelDialog.dismiss();
            }

            @Override
            public void onCancleClick() {
                // TODO Auto-generated method stub
                sureCancelDialog.dismiss();
            }
        }, "", "确定要取消本单追号吗？", "确定", "取消");
        sureCancelDialog.show();
    }
}
